class Api::V1::VersionsController < Api::V1::BaseController
	before_action :find_decision_or_iteration, only: [:index]
	before_action :set_version, only: [:show, :edit, :update, :destroy]

	def index
		if params[:decision_id]
			@versions = @decision.versions
		elsif params[:iteration_id]
			@versions = @iteration.versions
		else
			@versions = Version.all
		end
	end

	def create
		@version = Version.new(version_params)
		if @version.save
			render action: "show"
		else
			render :status => 406,
					:json => {
						:status_code => 406,
						:message => "Error creating resource!",
						:content => @version.errors.full_messages
					}		end
	end

	def show
	end

	def update
		if @version.update(version_params)
			render :status => 200,
					:json => { 
						:status_code => 200,
						:message => "Resource updated succesfully!",
						:content => ""
					}
		else
			render :status => 406, 
					:json => {
						:status_code => 406,
						:message => "Error updating resource!"
						:content => @version.errors.full_messages
					}
		end
	end

	def destroy
		if @version.destroy
			render :status => 200,
					:json => { 
						:status_code => 200,
						:message => "Resource deleted succesfully!",
						:content => ""
					}
		else
			render :status => 406, 
					:json => {
						:status_code => 406,
						:message => "Error deleting resource!",
						:content => @version.errors.full_messages
					}
		end
	end

	private

		def set_version
     		@version = Version.find(params[:id])
     		rescue ActiveRecord::RecordNotFound
				error = "The resource that you were looking for could not be found."
				render :status => 404, 
						:json => { 
							:status_code => 404,
							:message => error,
							:content => ""
						}
   		end

		def find_decision_or_iteration
			if params[:decision_id]
				@decision = Decision.find(params[:decision_id])
			elsif params[:iteration_id]
				@iteration = Iteration.find(params[:iteration_id])
			end
			rescue ActiveRecord::RecordNotFound
				error = "The resource that you were looking for could not be found."
				render :status => 404, 
						:json => { 
							:status_code => 404,
							:message => error,
							:content => ""
						}
		end

		def version_params
			params.require(:version).permit(:number, :state, :problem,:description, 
											:arguments, :iteration_id, :decision_id)
		end
end